package cn.com.miao.lynx.rpc.grpc.starter.service.impl;

import cn.com.miao.lynx.rpc.grpc.starter.GrpcService;
import cn.com.miao.lynx.rpc.grpc.starter.service.GrpcRequest;
import cn.com.miao.lynx.rpc.grpc.starter.service.GrpcResponse;
import cn.com.miao.lynx.rpc.grpc.starter.service.SerializeService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.google.protobuf.ByteString;

/**
 * FastJSONSerializeService
 * fastjson实现的序列化
 * @title: FastJSONSerializeService
 * @description:
 * @author: dengmiao
 * @create: 2019-12-25 15:51
 **/
public class FastJSONSerializeService implements SerializeService {

    @Override
    public ByteString serialize(GrpcResponse response) {
        return ByteString.copyFrom(JSON.toJSONBytes(response));
    }

    @Override
    public ByteString serialize(GrpcRequest request) {
        return ByteString.copyFrom(JSON.toJSONBytes(request));
    }

    @Override
    public GrpcRequest deserialize(GrpcService.Request request) {
        byte[] bytes = request.getRequest().toByteArray();
        return JSON.parseObject(bytes, GrpcRequest.class, Feature.OrderedField);
    }

    @Override
    public GrpcResponse deserialize(GrpcService.Response response) {
        byte[] bytes = response.getResponse().toByteArray();
        return JSON.parseObject(bytes, GrpcResponse.class, Feature.OrderedField);
    }
}
